package cn.zk.commom.tcp.obd;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import javax.annotation.PreDestroy;
import java.net.InetSocketAddress;

@Component
@Slf4j
public class ObdNettyServer implements CommandLineRunner {
    @Value("${tcp.obd.port}")
    private int port;
    @Value("${tcp.obd.ip}")
    private String ip;
    EventLoopGroup bossGroup = new NioEventLoopGroup(1);
    EventLoopGroup workerGroup = new NioEventLoopGroup();

    public void start(InetSocketAddress address) {
        try {
            ServerBootstrap bootstrap = new ServerBootstrap()
                    .group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .localAddress(address)
                    .childHandler(new ObdServerChannelInitializer())
                    .option(ChannelOption.SO_BACKLOG, 128)
                    .childOption(ChannelOption.SO_KEEPALIVE, true);
            // 绑定端口，开始接收进来的连接
            ChannelFuture future = bootstrap.bind(address).sync();
            log.info("obd接收服务启动成功!启动地址为:====>{}启动端口为:===>{}", address.getHostName(), address.getPort());
//            future.channel().closeFuture().sync();
        } catch (Exception e) {
        }
    }

    @Override
    public void run(String... args) throws Exception {
        //String IP = IpUtil.getLocalIP();
        String IP = "localhost";
        InetSocketAddress address = new InetSocketAddress(ip, port);
        this.start(address);
    }

    @PreDestroy
    public void destroy() throws InterruptedException {
        // 释放线程池资源
        workerGroup.shutdownGracefully().sync();
        bossGroup.shutdownGracefully().sync();
    }
}
